import datetime
import re
from web.utils import utils
from django.http import JsonResponse
from django.shortcuts import render, HttpResponse
from django.views.decorators.http import require_http_methods
from web.models import Plans, Files
from django.utils import timezone
from zipfile import ZipFile
import io


@require_http_methods(["GET"])
def index(request):
    query = request.GET.get("query", None)
    ID = request.session.get("ID")
    prefix = "/"
    # 默认链接
    itemLinks = [{"name": "Home", "url": "/home"}]
    # 获取该路径下的一级文件名称
    fileList = []
    if query == None:
        file = Files.objects.filter(user_ID=ID)
        # 记录子路径，避免重复计算
        childPath = []
        for i in range(len(file)):
            if len(file[i].path.split(prefix)) > 1:
                temp = "/" + file[i].path.split(prefix)[1]
                if temp not in childPath:
                    childPath.append(temp)
                    Dirs = utils.toDirs(temp, ID)
                    fileList.append(Dirs)
    else:
        fileList = Files.objects.filter(name__contains=query, user_ID=ID).values()
        for i in range(len(fileList)):
            fileList[i]['type'] = utils.isFilesOrDirs(fileList[i]['path'], fileList[i]['user_ID'])
        r = {"name": query + " 查找结果如下", "url": "#"}
        itemLinks.append(r)
    # 剩余容量
    remainSize = 0
    for file in fileList:
        remainSize = remainSize + int(file["size"])
    plan = request.session.get("plan")
    capacity = Plans.objects.get(plan=plan).memory_size
    capacity = int(capacity.split("g")[0]) * (1024**3)
    remainSize = round((capacity - remainSize) / (1024**3), 2)
    remainSize = str(remainSize) + "GB"
    return render(
        request,
        "web/homeSpace.html",
        {"fileList": fileList, "itemLinks": itemLinks, "remainSize": remainSize},
    )


# 上传功能
@require_http_methods(["POST"])
def upload(request):
    file = request.POST
    file_content = request.FILES["file"]
    ID = request.session.get("ID")
    name = str(file["name"])
    m_time = datetime.datetime.fromtimestamp(
        int(file["lastModified"]) / 1000, timezone.get_current_timezone()
    )
    m_time = m_time.strftime("%Y-%m-%d %H:%M:%S.%f")
    size = int(file["size"])
    path = str(file["webkitRelativePath"])
    # 文件导入数据库
    File = Files()
    File.user_ID = ID
    File.path = "/" + path
    File.name = name
    File.m_time = m_time
    File.size = size
    File.content = file_content.read()
    File.save()
    return HttpResponse(200)


# 搜索功能
@require_http_methods(["GET"])
def search(request):
    query = request.GET.get("query")
    return JsonResponse({"href": "/home?query=" + query})


# 下载功能
@require_http_methods(["GET"])
def download(request):
    ID = request.session.get("ID")
    path = request.GET.get("file_path")
    # 创建zip文件
    # 名称
    buffer = io.BytesIO()
    file_name = request.GET.get("file_path").split("/")[-1]
    # zip_name = file_name + ".zip"
    zip = ZipFile(buffer, mode="w")
    # 文件路径和内容
    file = Files.objects.filter(path__contains=path, user_ID=ID).values()
    for i in range(len(file)):
        # 写入zip文件
        path = file[i]["path"]
        content = file[i]["content"]
        zip.writestr(path, content)
    zip.close()
    # 构造下载链接
    response = HttpResponse(buffer.getvalue())
    response["Content-Type"] = "application/octet-stream"
    response["Content-Disposition"] = "attachment; filename=" + file_name
    return response

# 删除功能
@require_http_methods(["POST"])
def delete(request):
    file_path = request.POST.get("file_path")
    Files.objects.filter(path__contains=file_path).delete()
    return HttpResponse(200)


# 详情界面  接收 ID 与 path
@require_http_methods(["GET"])
def detailDirs(request, item):
    # path = request.GET.get('path',None)
    path = item.replace("+", "/")
    # 默认链接
    itemLinks = [{"name": "Home", "url": "/home"}]
    # 添加所有链接
    itempath = path.split("/")
    currentPath = ""
    for i in range(1, len(itempath)):
        currentPath = currentPath + "+" + itempath[i]
        c = {"name": itempath[i], "url": "/home/detailDirs/" + currentPath}
        itemLinks.append(c)

    file = Files.objects.values().filter(user_ID=request.session.get("ID"))
    # 获取该路径下的一级文件名称
    fileList = []
    # 记录子路径，避免重复计算
    childPath = []
    for i in range(len(file)):
        # 在t[i]['path']中去除src_path
        f = file[i]["path"].replace(path, "", 1)
        if f != file[i]["path"] and f != "":
            temp = path + "/" + f.split("/")[1]
            if temp not in childPath:
                childPath.append(temp)
                Dirs = utils.toDirs(temp, request.session.get("ID"))
                fileList.append(Dirs)
    # 剩余容量
    remainSize = 0
    for file in fileList:
        remainSize = remainSize + int(file["size"])
    plan = request.session.get("plan")
    capacity = Plans.objects.get(plan=plan).memory_size
    capacity = int(capacity.split("g")[0]) * (1024**3)
    remainSize = round((capacity - remainSize) / (1024**3), 2)
    remainSize = str(remainSize) + "GB"
    return render(
        request,
        "web/homeSpace.html",
        {"fileList": fileList, "itemLinks": itemLinks, "remainSize": remainSize},
    )


# 编辑文件
@require_http_methods(["GET"])
def editFile(request):
    path = request.GET.get("path", None)
    file = Files.objects.values("ID").filter(
        user_ID=request.session.get("ID"), path=path
    )

    path = "http://127.0.0.1:8000/home/doc/read/" + str(file[0]["ID"])
    return HttpResponse(path)
